package com.zhongxi.guoyuan.fragment;


import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseFragment;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.UpdateResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.ClearCacheUtils;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.DataUtil;
import com.zhongxi.guoyuan.utils.SpUtils;
import com.zhongxi.guoyuan.view.HtmlActivity;
import com.zhongxi.guoyuan.view.MainHomeActivity;
import com.zhongxi.guoyuan.view.personalCenter.BeanDynamicActivity;
import com.zhongxi.guoyuan.view.personalCenter.BeautifulStoreOrderActivity;
import com.zhongxi.guoyuan.view.personalCenter.ClearWeedExchangeActivity;
import com.zhongxi.guoyuan.view.personalCenter.HasConsumeHomeActivity;
import com.zhongxi.guoyuan.view.personalCenter.LogisticsSearchActivity;
import com.zhongxi.guoyuan.view.personalCenter.NewCollectActivity;
import com.zhongxi.guoyuan.view.personalCenter.RewardCoinOrderActivity;
import com.zhongxi.guoyuan.view.personalCenter.SystemMessageActivity;
import com.zhongxi.guoyuan.view.personalCenter.WithDrawCashActivity;
import com.zhongxi.guoyuan.view.shopCart.ShoppingCartActivity;
import com.zhongxi.guoyuan.view.user.UserInfoSettingActivity;

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * A simple {@link Fragment} subclass.
 */
public class MainPersonFragment extends BaseFragment {

    public static final int REQUESTNOPAY = 1234;
    private static final int REQUESTSETTING = 9969;
    @Bind(R.id.person_beauty)
    RelativeLayout personBeauty;
    @Bind(R.id.person_reward)
    RelativeLayout personReward;
    @Bind(R.id.person_cart)
    RelativeLayout personCart;
    @Bind(R.id.person_withdraw)
    RelativeLayout personWithdraw;
    @Bind(R.id.person_collect)
    RelativeLayout personCollect;
    @Bind(R.id.person_record)
    RelativeLayout personRecord;
    @Bind(R.id.person_bean_dynamic)
    RelativeLayout personBeanDynamic;
    @Bind(R.id.person_setting)
    RelativeLayout personSetting;
    @Bind(R.id.person_dynamic)
    RelativeLayout personDynamic;
    @Bind(R.id.person_delivery)
    RelativeLayout personDelivery;
    @Bind(R.id.person_cleanCache)
    RelativeLayout personCleanCache;
    @Bind(R.id.person_update)
    RelativeLayout personUpdate;
    @Bind(R.id.person_exit)
    RelativeLayout personExit;
    @Bind(R.id.person_rela_exchange)
    RelativeLayout personRelaExchange;
    @Bind(R.id.ivBack)
    ImageView ivBack;
    @Bind(R.id.ivBox)
    ImageView ivBox;
    @Bind(R.id.cachesize)
    TextView cachesize;
    private TextView tvUserName;

    private RelativeLayout person_rela_exchange;
    private TextView tvUserPhone;
    private TextView tvBonusPoint;
    private TextView tvIdentify;
    private ImageView ivUserHead;
    private String type;
    private UpdateResult result;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View mInflate = inflater.inflate(R.layout.activity_main_person, container, false);
        ButterKnife.bind(this, mInflate);
        return mInflate;
    }

    @Override
    protected void initView() {
        super.initView();
        initTitle();
        tvTitle.setText("个人中心");
        tvUserName = (TextView) getView().findViewById(R.id.tvUserName);
        tvUserPhone = (TextView) getView().findViewById(R.id.tvUserPhone);
        ivUserHead = (ImageView) getView().findViewById(R.id.ivUserHead);
        tvBonusPoint = (TextView) getView().findViewById(R.id.tvBonusPoint);  //红豆
        tvIdentify = (TextView) getView().findViewById(R.id.tvIdentify);  //红豆
        person_rela_exchange = (RelativeLayout) getView().findViewById(R.id.person_rela_exchange);
        ivBox.setVisibility(View.GONE);
        person_rela_exchange.setVisibility(View.VISIBLE);
    }

    @Override
    protected void initData() {
        super.initData();
        if (TextUtils.isEmpty(MyApplication.getInstance().getInnerCurrency())) {
            tvIdentify.setText("0 美豆");
        } else {
            tvIdentify.setText(MyApplication.getInstance().getInnerCurrency() + " 美豆");
        }
        if (TextUtils.isEmpty(MyApplication.getInstance().getHdCurrency())) {
            tvBonusPoint.setText("0 红豆");
        } else {
            tvBonusPoint.setText(DataUtil.formatDataSixPoint(MyApplication.getInstance().getHdCurrency()) + " 红豆");
        }
        if (null != MyApplication.getInstance().getUserName() && !"".equals(MyApplication.getInstance().getUserName())) {
            tvUserName.setText(MyApplication.getInstance().getUserName());
        } else {
            tvUserName.setText(R.string.app_name);
        }
        if (null != MyApplication.getInstance().getPhone() && !"".equals(MyApplication.getInstance().getPhone())) {
            tvUserPhone.setText(MyApplication.getInstance().getPhone());
        } else {
            tvUserPhone.setText("");
        }

        Glide.with(context)
                .load(Url.BASE_URL + MyApplication.getInstance().getAvatar())
                .placeholder(R.mipmap.logo)
//                .transform(new GlideRoundTransform(context, 20))
                .into(ivUserHead);

        try {
            if (ClearCacheUtils.getTotalCacheSize(context) != null) {
                cachesize.setText(ClearCacheUtils.getTotalCacheSize(context).toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick({R.id.ivBack, R.id.ivBox, R.id.person_rela_exchange, R.id.person_beauty, R.id.person_reward, R.id.person_bean_dynamic, R.id.person_cart, R.id.person_withdraw,
            R.id.person_collect, R.id.person_record, R.id.person_setting, R.id.person_dynamic, R.id.person_delivery,
            R.id.person_cleanCache, R.id.person_update, R.id.person_exit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                getActivity().finish();
                break;
            case R.id.ivBox:
                Intent intent = new Intent(context, HtmlActivity.class);
                intent.putExtra("type", "doudouRule");
                startActivity(intent);
                break;
            case R.id.person_rela_exchange://美豆兑换
                startAct(ClearWeedExchangeActivity.class);
                break;
            case R.id.person_beauty:
                Intent intentNopay = new Intent(context, BeautifulStoreOrderActivity.class);
                startActivityForResult(intentNopay, REQUESTNOPAY);
                break;
            case R.id.person_reward:
                startAct(RewardCoinOrderActivity.class);//超市订单列表
                break;
            case R.id.person_cart:
                startActivity(new Intent(context, ShoppingCartActivity.class));
                break;
            case R.id.person_withdraw:
                startAct(WithDrawCashActivity.class);//提现助手
                break;
            case R.id.person_collect:
//                startAct(MyCollectionActivity.class);//收藏
                startAct(NewCollectActivity.class);//收藏
                break;
            case R.id.person_record:
//                startAct(HasConsumeActivity.class);//消费记录
                startAct(HasConsumeHomeActivity.class);
                break;
            case R.id.person_bean_dynamic://豆豆动态
                startAct(BeanDynamicActivity.class);
                break;
            case R.id.person_setting:
                startActivityForResult(new Intent(context, UserInfoSettingActivity.class), REQUESTSETTING);
                break;
            case R.id.person_dynamic://系统消息
                startAct(SystemMessageActivity.class);
                break;
            case R.id.person_delivery://快递查询
                startAct(LogisticsSearchActivity.class);
                break;
            case R.id.person_cleanCache:
                ClearCacheUtils.clearAllCache(context);
                cachesize.setText("0KB");
                showShortToast("清理完成");
                break;
            case R.id.person_update:
                type = "update";
                getServer(Url.CHECK_UPD, null, "", false, null, "get");
                break;
            case R.id.person_exit:
                getLogout();
                if (null != MyApplication.getInstance().getUserId() || !"".equals(MyApplication.getInstance().getUserId())) {
                    MyApplication.getInstance().sharedPrefrences.edit().putString("phone", "").commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("userid", "").commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("username", "").commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("shopname", "").commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("rmb", "").commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("silver", "").commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("inner", "").commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("hd", "").commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("num", "").commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("avatar", "").commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putBoolean("shareHolder", false).commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putBoolean("privilege", false).commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("avatar", "").commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("rewardName", "").commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("rewardUserphone", "").commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddress", "").commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddressid", "").commit();
                    SpUtils.getInstance().saveSp("shopid", "");
                    SpUtils.getInstance().saveSp("mdffline", "");
                    SpUtils.getInstance().saveSp("orderid", "");
                    startAct(MainHomeActivity.class);
                    getActivity().finish();
                }
                break;
        }
    }

    private void getLogout() {
        type = "logout";
        getServer(Url.LOGOUT, null, "", false, null, "get");
    }


    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        if ("update".equals(type)) {
            result = gson.fromJson(response, UpdateResult.class);
            if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                MyApplication.getInstance().setSpValue(result.getSafeobj());
            }
            if (null != result.getUpdClient() && !"".equals(result.getUpdClient())) {
                if (null != result.getUpdClient().getDownUrl() && !"".equals(result.getUpdClient().getDownUrl())) {
                    downFile();
                }
            } else {
                isExists();
            }
        } else if ("logout".equals(type)) {
            BaseResponse mBaseResponse = gson.fromJson(response, BaseResponse.class);
        }
    }

    /**
     * 是否需要更新
     */
    int version = 0;
    HttpURLConnection conn = null;

    private void isExists() {
        version = Integer.parseInt(MyApplication.getInstance().getMinVersion()) + 1;
        new Thread(new Runnable() {
            @Override
            public void run() {
                URL url = null;
                try {
                    url = new URL(Url.APK_URL + version + Url.APK_URL_NAME);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(5000);
                    conn.connect();
                    if (conn.getResponseCode() == 200) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                downFile2();
                            }
                        });
                    } else {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showShortToast("已是最新版本");
                            }
                        });
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    private void downFile2() {
        AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_version, null);
        ImageView iv_Cancel = (ImageView) view.findViewById(R.id.iv_Cancel);
        TextView tv_dsc = (TextView) view.findViewById(R.id.tv_dsc);
        TextView tv_ok = (TextView) view.findViewById(R.id.tv_ok);
        adb.setView(view);
        tv_dsc.setText("发现新版本，请尽快更新");
        final AlertDialog dialog = adb.create();
        Window window = dialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.setOnKeyListener(keylistener);
        dialog.setCanceledOnTouchOutside(false);
        iv_Cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                System.exit(0);
            }
        });
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                downLoadApk2();
            }
        });
        dialog.show();
    }


    private void downLoadApk2() {
        final ProgressDialog pd; //进度条对话框
        pd = new ProgressDialog(getActivity());
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setProgress(1000);
        pd.setMessage("正在下载更新");
        pd.setOnKeyListener(keylistener);
        pd.setCanceledOnTouchOutside(false);
        pd.setProgressNumberFormat("%1d M/%2d M");
        pd.show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    File file = CommonTool.getFileFromServer(Url.APK_URL + version + Url.APK_URL_NAME, pd);
                    installApk(file);
                    pd.dismiss();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }


    private DialogInterface.OnKeyListener keylistener = new DialogInterface.OnKeyListener() {
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                getActivity().finish();
                return true;
            } else {
                return false;
            }
        }
    };

    private void downFile() {
        AlertDialog.Builder adb = new AlertDialog.Builder(context);
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_version, null);
        ImageView iv_Cancel = (ImageView) view.findViewById(R.id.iv_Cancel);
        TextView tv_dsc = (TextView) view.findViewById(R.id.tv_dsc);
        TextView tv_ok = (TextView) view.findViewById(R.id.tv_ok);
        adb.setView(view);
        if (null != result.getUpdClient().getDesc() && !"".equals(result.getUpdClient().getDesc())) {
            tv_dsc.setText(result.getUpdClient().getDesc());
        } else {
            tv_dsc.setText("发现新版本,请尽快更新");
        }
        final AlertDialog dialog = adb.create();
        dialog.setOnKeyListener(keylistener);
        dialog.setCanceledOnTouchOutside(false);
        iv_Cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                System.exit(0);
            }
        });
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                downLoadApk();
            }
        });
        dialog.show();
    }

    /**
     * 下载APK
     */
    private void downLoadApk() {
        final ProgressDialog pd; //进度条对话框
        pd = new ProgressDialog(context);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setProgress(1000);
        pd.setMessage("正在下载更新");
        pd.setOnKeyListener(keylistener);
        pd.setCanceledOnTouchOutside(false);
        pd.setProgressNumberFormat("%1d M/%2d M");
        pd.show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    File file = CommonTool.getFileFromServer(result.getUpdClient().getDownUrl(), pd);
                    installApk(file);
                    pd.dismiss();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //安装apk
    protected void installApk(File file) {
        if (file != null) {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
                Uri apkUri = FileProvider.getUriForFile(context, "com.zhongxi.guoyuan.fileprovider", file);//在AndroidManifest中的android:authorities值
                Intent install = new Intent(Intent.ACTION_VIEW);
                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加这一句表示对目标应用临时授权该Uri所代表的文件
                install.setDataAndType(apkUri, "application/vnd.android.package-archive");
                context.startActivity(install);
            } else {
                Intent intent = new Intent();
                //执行动作
                intent.setAction(Intent.ACTION_VIEW);
                //执行的数据类型
                intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        BaseResponse baseResponse = gson.fromJson(response, BaseResponse.class);
        if (null != baseResponse.getSafeobj() && !"".equals(baseResponse.getSafeobj())) {
            MyApplication.getInstance().setSpValue(baseResponse.getSafeobj());
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUESTSETTING) {
            Glide.with(context)
                    .load(Url.BASE_URL + MyApplication.getInstance().getAvatar())
                    .placeholder(R.mipmap.logo)
//                    .transform(new GlideRoundTransform(context, 20))
                    .into(ivUserHead);
            if (null != MyApplication.getInstance().getUserName() && !"".equals(MyApplication.getInstance().getUserName())) {
                tvUserName.setText(MyApplication.getInstance().getUserName());
            } else {
                tvUserName.setText(R.string.app_name);
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
